package com.solveit.aps.io.csv;

import java.text.NumberFormat;
import java.util.Locale;

public final class ImportToolsUtil {
	private ImportToolsUtil() {
		// Private constructor.
	}

	public static boolean getBoolean(final String inputString,
			final Boolean defaultValue) throws Exception {
		final boolean active;
		if (inputString == null || inputString.length() == 0) {
			active = defaultValue;
		} else {
			final String tempString = inputString.trim();
			if (tempString.equalsIgnoreCase("TRUE")
					|| tempString.equalsIgnoreCase("T")
					|| tempString.equalsIgnoreCase("YES")
					|| tempString.equalsIgnoreCase("Y")
					|| tempString.equalsIgnoreCase("1")) {
				active = true;
			} else if (tempString.equalsIgnoreCase("FALSE")
					|| tempString.equalsIgnoreCase("F")
					|| tempString.equalsIgnoreCase("NO")
					|| tempString.equalsIgnoreCase("N")
					|| tempString.equalsIgnoreCase("0")) {
				active = false;
			} else {
				throw new Exception("Cannot parse boolean: " + tempString);
			}
		}
		return active;
	}

	/**
	 * Note this returns industry standard percentage. 5% will be returned as
	 * 0.05.
	 * 
	 * @param inputString
	 * @param defaultValue
	 * @return
	 * @throws Exception
	 */
	public static Double getPercentage(final String inputString,
			final Double defaultValue) throws Exception {
		Double result;
		if (inputString == null || inputString.length() == 0) {
			result = defaultValue;
		} else {
			try {
				result = NumberFormat.getPercentInstance(Locale.US).parse(inputString)
						.doubleValue();
			} catch (final Exception e) {
				throw new Exception("Cannon parse percentage: " + inputString);
			}
		}
		return result;
	}

	public static Double getDouble(final String inputString,
			final Double defaultValue) throws Exception {
		Double result;
		if (inputString == null || inputString.length() == 0) {
			result = defaultValue;
		} else {
			try {
				result = NumberFormat.getNumberInstance(Locale.US).parse(inputString)
						.doubleValue();
			} catch (final Exception e) {
				throw new Exception("Cannon parse double: " + inputString);
			}
		}
		return result;
	}
}
